import { redirect } from 'react-router-dom'

export default async ({ request }) => {
  const formData = await request.formData()
  const data = Object.fromEntries(formData)

  switch (request.method) {
    // 新增
    case 'POST': {
      const id = await window.api.sql(
        `insert into categories (name,created_at) values ('未命名分类',datetime('now', '+8 hours'))`,
        'insert'
      )
      // 跳转路由
      return redirect(`/config/category/contentList/${id}`)
    }

    case 'DELETE': {
      // 删除分类
      await window.api.sql(`delete from categories where id = @id`, 'del', { id: data.id })
      // 将分类下面的片段移动到未分类目录下
      await window.api.sql(
        `update contents set category_id=0 where category_id=@category_id`,
        'update',
        { category_id: data.id }
      )
      // 跳转路由
      return redirect('/config/category/contentList')
    }

    // 更新分类
    case 'PUT': {
      await window.api.sql(`update categories set name=@name where id = @id`, 'update', data)
    }
  }

  return {}
}
